<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人档案系统</title>
    <style>
        @keyframes loading {
            from {
                transform: rotate(0deg);
            }

            to {
                transform: rotate(360deg);
            }
        }

        body {
            width: 100%;
            height: 100vh;
            background-color: #202020;
            overflow: hidden;
        }

        .file_main {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            position: relative;
        }

        .mask {
            width: 100%;
            height: 100%;
            background-color: #202020;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 9999;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .loaging {
            width: 40px;
            height: 40px;
            animation: loading 1s infinite linear;
        }

        .loaging>img {
            width: 100%;
        }

        #isClick {
            width: 100%;
            height: 100%;
            position: absolute;
            left: 0;
            top: 0;
            z-index: 9999;
        }

        .isClickHide {
            display: none;
        }

        #flipbook_box {
            position: relative;
        }

        .flipbook_box {
            overflow: hidden;
        }

        #flipbook {
            margin: 0 auto !important;
            box-shadow: 0 3px 15px #4d4c4c;
            cursor: pointer;
            background-color: #202020 !important;
            /* height: 800px!important; */
        }

        .flipbook {
            position: absolute;
        }

        #flipbook .cover {
            background: #333;
        }

        #flipbook .cover h1 {
            color: white;
            text-align: center;
            font-size: 50px;
            line-height: 500px;
            margin: 0px;
        }

        #flipbook .loader {
            width: 24px;
            height: 24px;
            display: block;
            position: absolute;
            top: 238px;
            left: 188px;
        }

        #flipbook .data {
            text-align: center;
            font-size: 40px;
            color: #999;
            line-height: 500px;
        }

        #flipbook .odd {
            background-image: -webkit-linear-gradient(left, #FFF 95%, #ddd 100%);
            background-image: -moz-linear-gradient(left, #FFF 95%, #ddd 100%);
            background-image: -o-linear-gradient(left, #FFF 95%, #ddd 100%);
            background-image: -ms-linear-gradient(left, #FFF 95%, #ddd 100%);
            box-shadow: 0 3px 15px #4d4c4c;
        }

        #flipbook .even {
            background-image: -webkit-linear-gradient(right, #FFF 95%, #ddd 100%);
            background-image: -moz-linear-gradient(right, #FFF 95%, #ddd 100%);
            background-image: -o-linear-gradient(right, #FFF 95%, #ddd 100%);
            background-image: -ms-linear-gradient(right, #FFF 95%, #ddd 100%);
            box-shadow: 0 3px 15px #4d4c4c;
        }

        .page {
            background-color: #fff;
        }

        .operate {
            width: 100%;
            padding: 30px;
            display: flex;
            justify-content: center;
        }

        .operate_item {
            color: white;
            cursor: pointer;
            padding: 10px 20px;
            background-color: #404040;
        }

        .operate_item:hover {
            /* color: #1989fa; */
            background-color: #252E36;
        }

        #inputId {
            width: 40px;
            border: none;
            outline: none;
            text-align: center;
            background-color: #B4BCC6;
        }

        input::-webkit-outer-spin-button {
            -webkit-appearance: none;
        }

        input::-webkit-inner-spin-button {
            -webkit-appearance: none;
        }

        /* Firefox */
        input[type='number'] {
            -moz-appearance: textfield;
        }

        .operate_goto {
            color: white;
            padding: 10px 20px;
            background-color: #404040;
        }

        .image_loading {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: rgba(0, 0, 0, 0.3);
            color: #fff;
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>

<body>
    <div class="file_main">
        <div class="mask" id="maskId">
            <div class="loaging">
                <img src="./loading.svg" alt="">
            </div>
        </div>
        <div id="isClick" class="isClickHide"></div>
        <div id="flipbook_box">
            <div id="flipbook" style="margin-left: 20%; background-color: #fff;"></div>
        </div>

        <div class="operate">
            <div class="operate_item" onclick="onfirstPageClick()">首页</div>
            <div class="operate_item" onclick="onPrevPageClick()">上一页</div>
            <div class="operate_item" onclick="onNextPageClick()">下一页</div>
            <div class="operate_item" onclick="onLastPageClick()">尾页</div>
            <div class="operate_goto">
                <span>跳转至</span>
                <input id="inputId" type="number" onblur="handleBlurInput()" />
                <span>页</span>
            </div>
        </div>
    </div>

    <script src="./js/modernizr.2.5.3.min.js"></script>
    <script src="./js/jquery.min.1.7.js"></script>

    <script>
        var idList = [];
        var imageUrlArrNumber = 0;
        var imageUrlArr = [];
        var search = window.location.search.split('&');
        var hostname = 'https://books.edoc2.com';
        // var hostname = window.location.origin || '';
        var hostOrigin = hostname;
        // var token = search[0].split('=')[1] || '';
        // var fileIds = search[1].split('=')[1] || '';
        var token = '0034692309555f474f8db0bb39be85c0cdb3';
        var fileIds = '76';

        //TODO: 该判断部署生产环境时去掉
        // if (hasValue(hostname, '178')) {
            hostname = hostname.split(':')[0] + ':' + hostname.split(':')[1];
        // } else {
        //     hostname = hostname.split(':')[0] + ':' + hostname.split(':')[1] + ':20180';
        // }
        
        function hasValue(host, value) {
            return host.indexOf(value) === -1 ? false : true;
        }

        // 处理图片url显示
        function handleImagesUrl(id) {
            let url = '';
            $.ajax({
                url: `${hostname}/downLoad/DownLoadCheck?fileIds=${id}&r=28341&isIe=false&token=${token}`,
                async: false,
                success: function (res) {
                    url = `${hostname}/downLoad/index?fileIds=${id}&r=10582&regionHash=${res.RegionHash}`;
                }
            });
            return url;
        }
        // 获取图片id集
        function getImagesListIds() {
            let result = [];
            $.ajax({
                url: `${hostOrigin}/api/Res/Statistics/GetFileIdListById?fileId=${fileIds}`,
                async: false,
                success: function (res) {
                    result = JSON.parse(res.msg);
                }
            });
            return result || [];
        }
        // 获取图片集
        function getImagesLists(n1, n2, is = false, n3) {
            let urlArr = [];
            if (idList.length <= 0) {
                idList = getImagesListIds();
            }
            imageUrlArrNumber = idList.length;
            if (is) {
                urlArr = handleImagesUrl(idList[n3]);

            } else {
                for (let i = n1; i < n2; i++) {
                    console.log('i', i)
                    const url = handleImagesUrl(idList[i]);
                    urlArr.push(url);
                }
            }
            return urlArr;
        }

        imageUrlArr = getImagesLists(0, 3);

        var size = 0.9; // 按flipbookWidth标准大小缩放倍数
        var flipbookWidth = 524; // // 文件预览区域宽
        var flipbookHeight = 900; // 文件预览区域高
        var proportion = 2; // 宽高比
        var currentPage = 1; // 当前页数（包括封面）
        var isSinglePage = true; // 是否仅展示单页
        var isTurning = true; // 是否要触发turning事件中的逻辑
        var flipbook = $("#flipbook");
        var flipbookBox = $("#flipbook_box");

        function setSize() {
            const bodyWidth = document.body.clientWidth / 2; //网页可见区域宽
            const diff = bodyWidth / flipbookWidth;
            if (diff < 1) {
                size = diff - 0.2;
            }
        }
        setSize();
        
        // 隐藏loading
        function hideLoading() {
            $("#maskId").hide('fast');
        }

        // 页码输入框失焦事件
        function handleBlurInput() {
            var inputDom = $("#inputId");
            var value = inputDom[0].value;
            if (value) {
                value = Number(value)
            } else {
                return;
            }
            if (value <= 0 || value > imageUrlArrNumber) {
                alert('不存在该页面');
                return;
            }
            if (value === 1) {
                onfirstPageClick();
                return;
            }
            if (value <= imageUrlArrNumber && value >= (imageUrlArrNumber - 1)) {
                onLastPageClick();
                return;
            }
            flipbook.turn("page", value);
            recordCurrPage(value);
            setTimeout(() => {
                inputDom[0].value = '';
            })
        }
        // 展示一个页面
        function initPageShow() {
            flipbook.css({ left: `-${flipbookWidth * size}px`, });
            flipbook.addClass('flipbook');
            flipbookBox.css({ width: (flipbookWidth * size) + 'px' });
            flipbookBox.addClass('flipbook_box');
        }
        // 展示两个页面
        function changePageShow() {
            flipbook.css({ left: 0 });
            flipbook.removeClass('flipbook')
            flipbookBox.css({ width: (flipbookWidth * size * 2) + 'px' });
            flipbookBox.removeClass('flipbook_box')
        }
        // 获取封面图宽高
        function readImageSize() {
            if (imageUrlArr && imageUrlArr.length <= 0) return;
            // var image = document.createElement('img');
            return new Promise((resolve, reject) => {
                try {
                    const image = new Image();
                    image.src = imageUrlArr[0];
                    image.onload = function () {
                        proportion = image.height / image.width;
                        if (isNaN(proportion)) {
                            proportion = 1.5;
                        }
                        resolve(true);
                    }
                } catch (error) {
                    reject(false);
                }
            })
        }
        // 记录当前页码
        function recordCurrPage(num) {
            console.log('记录当前页码', num);
            if (num) {
                currentPage = num;
            } else {
                currentPage = flipbook.turn('page');
            }
            if (currentPage == 1 && !isSinglePage) {
                isSinglePage = true;
                $("#flipbook").animate({ left: `-${flipbookWidth * size}px` }, "normal");
                initPageShow();
            } else {
                isSinglePage = false;
                $("#flipbook").animate({ left: `0px` }, "normal");
                changePageShow();
            }
        }
        // 添加页面
        function addPage(pages) {
            for (let i = 0; i < pages.length; i++) {
                $('#isClick').removeClass('isClickHide')
                const url = getImagesLists(null, null, true, pages[i])
                let id = 'canvaspage' + pages[i]
                let div = document.createElement('div');
                div.style = `width: ${flipbookWidth * size}px; display: flex; justify-items: center; align-items: center; overflow: hidden`;
                const urlParam = url.split('?')[1];
                const urlParamFileIds = urlParam.split('&')[0];
                const fileIds = urlParamFileIds.split('=')[1];
                if (fileIds == 'undefined') {
                    $('#isClick').addClass('isClickHide')
                    flipbook.turn('addPage', div, pages[i])
                    return;
                }
                div.innerHTML = `<div class='image_loading' id='image_loading_${pages[i]}'>loading...</div>`
                flipbook.turn('addPage', div, pages[i])

                let image = document.createElement('img');
                image.src = url;
                image.style = "width: 100%";
                console.log();
                div.appendChild(image);
                image.onload = function () {
                    $(`#image_loading_${pages[i]}`).css({ display: 'none' });
                    $('#isClick').addClass('isClickHide')
                }
            }

        }
        // 上一页
        function onPrevPageClick() {
            console.log('上一页')
            flipbook.turn("previous");
            if (currentPage == 1) {
                onfirstPageClick();
                return;
            }
            recordCurrPage();
        }
        // 下一页
        function onNextPageClick() {
            flipbook.turn("next");
            recordCurrPage();
        }
        // 首页
        function onfirstPageClick() {
            isTurning = false;
            isSinglePage = false;
            recordCurrPage(1);
            flipbook.turn("page", currentPage);
        }
        // 尾页
        function onLastPageClick() {
            isTurning = false;
            isSinglePage = false;
            recordCurrPage(imageUrlArrNumber);
            flipbook.turn("page", imageUrlArrNumber);
        }
        // 页面渲染
        function rander() {
            for (let i = 0; i < 3; i++) {
                var id = 'canvaspage' + i
                var div = document.createElement('div');
                div.style = `width: ${flipbookWidth * size}px; display: flex; justify-content: center; align-items: center; overflow: hidden`;
                div.innerHTML = `<img style="height: 100%" src="${imageUrlArr[i]}" alt="">`
                flipbook.append(div)
            }

            //调用turn
            yepnope({
                test: Modernizr.csstransforms,
                yep: ['./js/turn.js'],
                complete: loadApp
            })
        }
        // turn.js
        function loadApp() {
            $("#flipbook").turn({
                width: flipbookWidth * 2 * size,
                height: flipbookWidth * proportion * size,
                elevation: 50,
                autoCenter: true,
                duration: 1000,
                gradients: true,
                pages: imageUrlArrNumber,
                // display: 'single',
                when: {
                    start: function () { },
                    end: function () {
                        console.log('currentPage', currentPage)
                        // if (currentPage == 3) {
                        //     onfirstPageClick();
                        // }
                    },
                    first: function () {
                        isSinglePage = true
                    },
                    last: function () {
                        isSinglePage = true
                    },
                    missing: function (e, pages) {
                        addPage(pages);
                    },
                    turning: function (e, page, view) {
                        console.log(page, 'page')
                        // if(page == 1) {
                        //     recordCurrPage(1)
                        // }
                        if (isTurning) {
                            recordCurrPage(page);
                        } else {
                            isTurning = true;
                        }
                    },
                    turned: function () {
                        setTimeout(() => {
                            hideLoading();
                        }, 300)
                    },
                    zooming: function () { },
                },
            })
        }


        // 初始化页面
        async function initPage() {
            initPageShow();
            await readImageSize();
        }
        window.onload = async function () {
            await initPage();
            await rander();
        }

    </script>
</body>

</html>